﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using ContentAppBase.Model;
using ContentAppBase.Model.Bing;
using ContentAppBase.ViewModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace ContentAppBase.View
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Common.LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            DataTransferManager.GetForCurrentView().DataRequested += MainPage_DataRequested;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            DataTransferManager.GetForCurrentView().DataRequested -= MainPage_DataRequested;
        }

        void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var vm = (MainViewModel)this.DataContext;

            args.Request.Data.Properties.Title = vm.Title;
            args.Request.Data.SetUri(vm.ShareUrl);
        }

        private void pageRoot_Loaded(object sender, RoutedEventArgs e)
        {
            ((MainViewModel)this.DataContext).InitCommand.Execute(null);
            this.groupGridView.ItemsSource = this.groupedItemsViewSource.View.CollectionGroups;
            this.groupGridViewSnapped.ItemsSource = this.groupedItemsViewSource.View.CollectionGroups;
        }

        private void ButtonHeader_Click(object sender, RoutedEventArgs e)
        {
            var list = (GroupInfoList<object>)((FrameworkElement)sender).DataContext;
            if (list.Count > 0)
            {
                var firstItem = list.FirstOrDefault();
                if (firstItem is SimpleItem && ((SimpleItem)firstItem).Type == SimpleItemType.ImageResults)
                    Frame.Navigate(typeof(SectionPage), "image");
                else if (firstItem is SimpleItem && ((SimpleItem)firstItem).Type == SimpleItemType.WebResults)
                    Frame.Navigate(typeof(SectionPage), "web");
            }
        }

        private void ImageGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            Launcher.LaunchUriAsync(new Uri(((ImageResult)e.ClickedItem).SourceUrl, UriKind.Absolute));
        }

        private void WebGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            Launcher.LaunchUriAsync(new Uri(((WebResult)e.ClickedItem).Url, UriKind.Absolute));
        }

        private void RichTextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            var block = (RichTextBlock)sender;
            var paragraph = new Paragraph();
            var rawString = (String)((SimpleItem)block.DataContext).Content;

            var parts = Regex.Split(rawString, "<h1>");

            for (int i = 0; i < parts.Length; i++)
            {
                var part = parts[i];
                if (part.Contains("</h1>"))
                {
                    var subparts = Regex.Split(part, "</h1>");
                    if (subparts.Length > 1)
                    {
                        if (!String.IsNullOrEmpty(parts[0]) || i > 1)
                            paragraph.Inlines.Add(new LineBreak());

                        paragraph.Inlines.Add(new Run() { Text = subparts[0], FontWeight = FontWeights.SemiBold });
                        paragraph.Inlines.Add(new Run() { Text = subparts[1] });
                    }
                }
                else
                {
                    paragraph.Inlines.Add(new Run() { Text = part });
                }
            }

            block.Blocks.Clear();
            block.Blocks.Add(paragraph);
        }

        private void LegalNotice_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            var vm = (MainViewModel)this.DataContext;
            Launcher.LaunchUriAsync(vm.ShareUrl);
        }

        private void SemanticZoomFullscreen_ViewChangeStarted(object sender, SemanticZoomViewChangedEventArgs e)
        {
            var vm = (MainViewModel)this.DataContext;
            vm.IsZoomedIn = !e.IsSourceZoomedInView;
        }
    }
}
